package com.rnkrsoft.suyan.config.protocol.v2;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.Serializable;
import java.nio.charset.Charset;

public class JsonDataConverter implements DataConverter{
    private static Gson GSON = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
    @Override
    public byte[] serialize(Serializable val) {
        if (val == null){
            return new byte[0];
        }
        String json = GSON.toJson(val);
        return json.getBytes(Charset.forName("UTF-8"));
    }

    @Override
    public <T extends Serializable> T deserialize(byte[] bytes, Class<T> javaType) {
        if (bytes == null){
            throw new IllegalArgumentException("bytes is null");
        }
        String json = new String(bytes, Charset.forName("UTF-8"));
        return GSON.fromJson(json, javaType);
    }

}
